The keywords break and continue are used within a loop to abort looping entirely or to jump to the next iteration immediately. You need to be aware of the following facts when using the keywords:
continue or break if the keyword is not enclosed by a loop.continue or break is enclosed by several loops, it affects only the innermost loop that encloses it.The keyword continue is used inside a loop to immediately start the next iteration, without executing the remaining statements in the current iteration.
continue. for i = 1:15
if i <= 10
continue
end
disp(i)
end
11.000
12.000
13.000
14.000
15.000
j >= 2 is satisfied, continue is invoked and hence it skips printing out j. The continue statement does not affect the outmost loop. Therefore, the statement i has not been skipped. All values of i have been printed out.for i = 1:5
for j = 1:5
if j >= 2
continue
end
j
end
i
end
j =
1.0000
i =
1.0000
j =
1.0000
i =
2.0000
j =
1.0000
i =
3.0000
j =
1.0000
i =
4.0000
j =
1.0000
i =
5.0000
You use break inside a loop to immediately exit the loop without executing the remaining statements in the current iteration.
break. for i = 1:100
if i > 10
break
end
disp(i)
end
1.0000
2.0000
3.0000
4.0000
5.0000
6.0000
7.0000
8.0000
9.0000
10.000
j >= 2 is satisfied, break is invoked and hence it exists the inner loop (j-loop). Note that break does not exit the outer loop. Therefore, all values of i have been printed out.for i = 1:5
for j = 1:5
if j >= 2
break
end
j
end
i
end
j =
1.0000
i =
1.0000
j =
1.0000
i =
2.0000
j =
1.0000
i =
3.0000
j =
1.0000
i =
4.0000
j =
1.0000
i =
5.0000
switch StatementThe keywords break and continue are only allowed inside a loop. When they are found in a switch statement enclosed by loops, they only affect the innermost loop that encloses the switch statement. That means, a switch statement propagates the effect of break or continue to the innermost loop containing them. See the following two examples for illustration.
continue within a switch statement) Because of the continue keyword, it skips printing i's value when i >= 5. The keyword continue only has an effect on the loop.value = 2;
for i = 1:10
switch value
case 1
% Do something
case 2
if i >= 5
continue
end
end
i
end
i =
1.0000
i =
2.0000
i =
3.0000
i =
4.0000
break within a switch statement) Because of the break keyword, it exists the for loop when i >= 5. break only has an effect on the loop.value = 2;
for i = 1:10
i
switch value
case 1
% Do something
case 2
if i >= 5
break
end
end
end
i =
1.0000
i =
2.0000
i =
3.0000
i =
4.0000
i =
5.0000